﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Health;
using SDS.SPHealthAnalyzerRules.Delegation.Helpers;

namespace SDS.SPHealthAnalyzerRules.Delegation.Rules
{
    ///// <summary>
    ///// ensures that any SharePoint sites configured for NEGO2, are not using Kernel Mode Authentication
    ///// </summary>
    ///// <see cref="http://technet.microsoft.com/en-us/library/cc771945.aspx" />
    //public class WebApps__KernelModeAuth_when_not_using_NEGO2 : SPHealthAnalysisRule
    //{
    //    private Guid CorrelationToken = Guid.NewGuid();

    //    [System.Diagnostics.DebuggerDisplay("{ServerName}/{WebAppName} using {AuthProviders}")]
    //    private struct Error
    //    {
    //        public string ServerName;
    //        public string WebAppName;
    //        public string AuthProviders;
    //    }
    //    readonly private List<Error> Errors = new List<Error>();

    //    public override SPHealthCategory Category { get { return SPHealthCategory.Configuration; } }

    //    public override SPHealthAnalysisRuleAutomaticExecutionParameters AutomaticExecutionParameters
    //    {
    //        get
    //        {
    //            return new SPHealthAnalysisRuleAutomaticExecutionParameters()
    //            {
    //                Schedule = SPHealthCheckSchedule.Daily,
    //                Scope = SPHealthCheckScope.All,
    //                ServiceType = typeof(SPWebService),
    //                RepairAutomatically = false
    //            };
    //        }
    //    }

    //    public override SPHealthCheckStatus Check()
    //    {
    //        // return variable, defualt value
    //        SPHealthCheckStatus outval = SPHealthCheckStatus.Failed;

    //        // log
    //        LoggingService.Write(LoggingService.Category_WebApp, TraceSeverity.Verbose, "Executing Health Check", CorrelationToken);

    //        // running as the system account
    //        Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate { doCheck(); });

    //        // set return value
    //        outval = Errors.Count == 0
    //             ? SPHealthCheckStatus.Passed
    //             : SPHealthCheckStatus.Failed;

    //        // log
    //        LoggingService.Write(
    //            LoggingService.Category_WebApp,
    //            TraceSeverity.Verbose,
    //            String.Format("Health Check completed with outcome {0}", outval.ToString()),
    //            CorrelationToken);

    //        return outval;
    //    }

    //    public override SPHealthCheckErrorLevel ErrorLevel
    //    {
    //        get
    //        {
    //            return SPHealthCheckErrorLevel.Error;
    //        }
    //    }
    //    public override string Summary { get { return "DELEGATION: Kernel-Mode Authentication disabled"; } }
    //    public override string Explanation
    //    {
    //        get
    //        {
    //            var x = Errors.Select(e => String.Format(@"Server [{0}] Web Application [{1}]",
    //                                                      e.ServerName,
    //                                                      e.WebAppName))
    //                          .ToArray();
    //            return String.Format(@"Web Applications using Windows Authentication provider [Negotiate:Kerberos] must not use Kernel-Mode authentication. The following violations were found.{0} {1}", Environment.NewLine, String.Join(Environment.NewLine, x));
    //        }
    //    }
    //    public override string Remedy
    //    {
    //        get { return String.Format("Remove the [Negotiate:Kerberos] authentication provider, or disable Kernel-mode authentication."); }
    //    }




    //    public void doCheck()
    //    {
    //        try
    //        {

    //            // if current server is running SPWebService (web apps)
    //            var Server = Microsoft.SharePoint.Administration.SPServer.Local;
    //            if (Server.isRunning<SPWebService>())
    //            {
    //                // looking for webapps using kerberos
    //                Server.WebApplications()
    //                      .Select(wa => new { WebApp = wa, AuthProviders = wa.WindowsAuthenticationProviders() })
    //                      .Where(x => !x.AuthProviders.Contains("Negotiate:Kerberos"))
    //                      .Where(x => !x.WebApp.WindowsAuthentication_usingKernelMode())
    //                      .ToList()
    //                      .ForEach(x =>
    //                      {
    //                          Errors.Add(new Error()
    //                          {
    //                              ServerName = Server.Name,
    //                              WebAppName = x.WebApp.DisplayName,
    //                              AuthProviders = String.Join(", ", x.AuthProviders.ToArray())
    //                          });
    //                      });

    //            } // FOREACH Server

    //        } // try
    //        catch (Exception ex)
    //        {
    //            LoggingService.Write(
    //                LoggingService.Category_WebApp,
    //                TraceSeverity.High,
    //                String.Format("Health Check encountered the following exception: {0}", ex.Message),
    //                CorrelationToken);
    //        }

    //    } // doCheck()

    //}
}
